package com.example.sunsg.okhttptest.model;

import android.content.ContentResolver;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.support.annotation.NonNull;

import com.breadtrip.R;
import com.example.sunsg.okhttptest.Manager.ImageManager;
import com.example.sunsg.okhttptest.bean.Image;
import com.example.sunsg.okhttptest.bean.ImageList;
import com.example.sunsg.okhttptest.bean.LocalItem;
import com.example.sunsg.okhttptest.util.BitmapManager;
import com.example.sunsg.okhttptest.util.Util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sunsg on 16/2/29.
 */
public class LifeStoryActivityModel {
    private static final String CAMERA_BUCKET = ImageManager.CAMERA_IMAGE_BUCKET_ID;

    private boolean mAbort = false;//是否中断异步任务
    Handler mHandler = new Handler(); // handler for the main thread
    private Thread mWorkerThread;//异步工作线程

    private CallBackLifeStoryActivity mCallBackLifeStoryActivity;
    private Context mContext;
    public LifeStoryActivityModel(CallBackLifeStoryActivity callBackLifeStoryActivity, Context context){
        mCallBackLifeStoryActivity = callBackLifeStoryActivity;
        mContext = context;
        startCheckImageWork();
    }

    /**
     * 启动检查手机相册线程
     */
    private void startCheckImageWork(){
        mAbort = false;
        mWorkerThread = new Thread("LifeSelectModel Worker") {
            @Override
            public void run() {
                workerRun();
            }
        };
        BitmapManager.instance().allowThreadDecoding(mWorkerThread);
        mWorkerThread.start();
    }

    // This is run in the worker thread.
    private void workerRun() {// 获取数据的任务

        final ArrayList<LocalItem> allItems = new ArrayList<LocalItem>();
        checkAllImageList(allItems);
        if(mAbort)
            return;
        checkImageList(allItems);
        if (mAbort)
            return;

        checkBucketIds(allItems);
        if (mAbort)
            return;

        checkLowStorage();

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                updateItems(allItems);
            }
        });
    }

    /**
     * 获得 buckedId 的imagelist
     * @param buckedId 如果  bucedid == null 查询所有的图片
     */
    public ImageList getImageList(String buckedId){
        return createImageList(ImageManager.INCLUDE_IMAGES, buckedId, mContext.getContentResolver());
    }

    /**
     * 获得 buckedId 的 所有图片
     * @param buckedId
     * @return
     */
    public List<Image> getImages(String buckedId){
        List<Image> images = new ArrayList<>();
        ImageList list = getImageList(buckedId);
        int len = list.getCount();
        Image image = null;
        for (int i = 0; i < len; i++) {
            image =  list.getImageAt(i);
            images.add(image);
        }
        return images;
    }

    /**
     * 排序
     * @param images
     * @return
     */
    public void sortImages(List<Image> images){
        Collections.sort(images, new Comparator<Image>() {
            @Override
            public int compare(Image lhs, Image rhs) {
                return lhs.getDateTaken() > rhs.getDateTaken() ? 1 : -1;
            }
        });
    }

    /**
     * 从 image 获取时间
     * @param image
     * @return
     */
    public String getDate(@NonNull Image image){
        return Util.getFormatTime(image.getDateTaken(),"yyyy-MM-dd") + Util.getWeek(image.getDateTaken());
    }

    public int getIndex(int index){
        return index % 3;
    }


    /**
     * 获取所有的图片 数量 第一张图片
     * @param allItems
     */
    private void checkAllImageList(ArrayList<LocalItem> allItems) {
        final ImageList list = createImageList(ImageManager.INCLUDE_IMAGES,
                null, mContext.getContentResolver());
        if (mAbort)
            return;
        LocalItem item = null;
        if (!list.isEmpty()) {
            item = new LocalItem(LocalItem.TYPE_ALL_IMAGES, null, mContext.getResources()
                    .getString(R.string.all), list.getImageAt(0),
                    list.getCount());
            allItems.add(item);
            list.close();
        }

    }

    /**
     * 根据bucked_id 获取相应 bucked_id 中所包含的图片的数量以及第一张图片
     * @param allItems
     */
    private void checkImageList(ArrayList<LocalItem> allItems) {

        ImageList list = createImageList(ImageManager.INCLUDE_IMAGES, ImageManager.CAMERA_IMAGE_BUCKET_ID, mContext.getContentResolver());
        if (mAbort)
            return;
        LocalItem item = null;
        if (!list.isEmpty()) {
            item = new LocalItem(LocalItem.TYPE_CAMERA_IMAGES, ImageManager.CAMERA_IMAGE_BUCKET_ID, mContext.getResources().getString(R.string.tv_albums), list.getImageAt(0), list.getCount());
            allItems.add(item);
            list.close();
        }
    }

    /**
     * 获得 bucketids
     * @param allItems
     */
    private void checkBucketIds(ArrayList<LocalItem> allItems) {
        HashMap<String, String> hashMap = ImageManager.getBucketIds(mContext.getContentResolver(), ImageManager.STORAGE_URI);
        if (mAbort)
            return;

        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
            String key = entry.getKey();
            if (key == null) {
                continue;
            }
            if (!key.equals(CAMERA_BUCKET)) {
                ImageList list = createImageList(ImageManager.INCLUDE_IMAGES, key, mContext.getContentResolver());
                if (mAbort)
                    return;

                LocalItem item = new LocalItem(LocalItem.TYPE_NORMAL_FOLDERS, key, entry.getValue(), list.getImageAt(0), list.getCount());
                allItems.add(item);
                list.close();
            }
        }

    }
    private static final long LOW_STORAGE_THRESHOLD = 1024 * 1024 * 2;
    // This is run in the worker thread.
    private void checkLowStorage() {
        // Check available space only if we are writable

        String storageDirectory = Environment
                .getExternalStorageDirectory().toString();
        StatFs stat = new StatFs(storageDirectory);
        long remaining = (long) stat.getAvailableBlocks()
                * (long) stat.getBlockSize();
        if (remaining < LOW_STORAGE_THRESHOLD) {
            mHandler.post(new Runnable() {
                public void run() {
                    checkLowStorageFinished();
                }
            });
        }

    }

    // This is run in the main thread.
    // This is called only if the storage is low.
    private void checkLowStorageFinished() {

    }

    /**
     * 获得图片
     * @param mediaTypes
     * @param bucketId
     * @param cr
     * @return
     */
    private ImageList createImageList(int mediaTypes, String bucketId, ContentResolver cr) {
        ImageList list = ImageManager.makeImageList(cr, ImageManager.DataLocation.ALL, mediaTypes, ImageManager.SORT_DESCENDING, bucketId);
        return list;
    }

    public void updateItems(List<LocalItem> itmes){
        if(mCallBackLifeStoryActivity != null){
            mCallBackLifeStoryActivity.setItems(itmes);
        }
    }

    /**
     * activity 回调接口
     */
    public interface CallBackLifeStoryActivity {
        void setItems(List<LocalItem> itmes);
    }
}
